package com.listeningframework.boot.autoconfigure.webmvc.validate;

import com.listeningframework.boot.commons.string.RegExpUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author lixining
 * @version $Id: ListeningNotBlankValidator.java, v 0.1 2016年5月5日 下午4:19:01 lixining Exp $
 * NotBlank Length Validator
 */
public class ListeningPatternValidator implements ConstraintValidator<ListeningPattern, String> {
    /**
     * Error Message
     */
    private String message;
    /**
     * Pattern
     */
    private String pattern;

    /**
     * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
     */
    @Override
    public void initialize(ListeningPattern constraintAnnotation) {
        this.message = constraintAnnotation.message();
        this.pattern = constraintAnnotation.pattern();
    }

    /**
     * @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (RegExpUtils.matches(pattern, value)) {
            return true;
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        return false;
    }

}
